package com.gmq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmq.common.BaseContext;
import com.gmq.common.R;
import com.gmq.entity.AddressBook;
import com.gmq.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private BaseContext baseContext;

    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        log.info("查询用户地址");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = baseContext.getThreadLocal();
        queryWrapper.like(AddressBook::getUserId, userId);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }

    @GetMapping("/default")
    public R<AddressBook> defaultAddress() {
        log.info("查询默认地址");
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = baseContext.getThreadLocal();
        queryWrapper.like(AddressBook::getUserId, userId);
        queryWrapper.like(AddressBook::getIsDefault, 1);
        AddressBook bookServiceOne = addressBookService.getOne(queryWrapper);
        return R.success(bookServiceOne);
    }

    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址{}", addressBook);
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = baseContext.getThreadLocal();
        queryWrapper.like(AddressBook::getUserId, userId);
        queryWrapper.like(AddressBook::getIsDefault, 1);
        AddressBook bookServiceOne = addressBookService.getOne(queryWrapper);
        bookServiceOne.setIsDefault(0);
        addressBookService.updateById(bookServiceOne);
        //设置默认地址
        AddressBook bookServiceById = addressBookService.getById(addressBook.getId());
        bookServiceById.setIsDefault(1);
        addressBookService.updateById(bookServiceById);
        return R.success("修改成功");
    }

    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(baseContext.getThreadLocal());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }
}
